package com.example.coinhelper.Fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.se.omapi.Session;
import android.util.TimeUtils;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.coinhelper.Activity.AnalyticsActivity;
import com.example.coinhelper.Activity.RecordActivity;
import com.example.coinhelper.Activity.SearchActivity;
import com.example.coinhelper.Adapter.DetailsAdapter;
import com.example.coinhelper.Bean.Details;
import com.example.coinhelper.Manage.DetailsManage;
import com.example.coinhelper.R;
import com.example.coinhelper.utils.MySesseion;
import com.example.coinhelper.utils.MySharedViewModel;

import com.example.coinhelper.utils.TimeUtility;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link DetailsFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class DetailsFragment extends Fragment implements View.OnClickListener {


    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private DetailsAdapter detailsAdapter;

    private DetailsManage detailsManage;

    ListView todayLv;
    // 声明数据源
    ImageView searchIv;
    ImageButton btn_edit;
    //    List<AccountBean> mDatas;
//    AccountAdapter adapter;
    int year, month, day;
    View headerView = null;
    // 头布局相关控件
    TextView topOutTv, topInTv, topbudgetTv, topConTv;
    ImageView topShowIv;
    List<Details> detailsList;

    int MENU_UPDATE = 0;
    int MENU_DELETE = 1;

    public DetailsFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment DetailsFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static DetailsFragment newInstance(String param1, String param2) {
        DetailsFragment fragment = new DetailsFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }


    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_details, container, false);


        return view;
//        return inflater.inflate(R.layout.fragment_details, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // 在这里设置监听器
        initView(view);
        initTime();
        addLVHeaderView();
        //setLVLongClickListener();
        update_top();
//        setSlideDeleteListener(view);
        // 其他相关的设置监听器的操作

    }

    private void initView(View view) {

        todayLv = view.findViewById(R.id.main_lv);
        btn_edit = view.findViewById(R.id.main_btn_edit);
        searchIv = view.findViewById(R.id.main_iv_search);
        btn_edit.setOnClickListener(this);
        searchIv.setOnClickListener(this);
        //setLVLongClickListener();
        registerForContextMenu(todayLv);
        setScrollListener();
        detailsManage = new DetailsManage(requireContext());
        detailsList = detailsManage.getAllDetailsByUsername(MySesseion.USER.getUsername());
        detailsAdapter = new DetailsAdapter(requireContext(), detailsList);
        ListView listViewDetailView = view.findViewById(R.id.main_lv);
        listViewDetailView.setAdapter(detailsAdapter);
        MySesseion.DETAILSADAPTER = detailsAdapter;


    }
    @Override
    public void onResume() {
        super.onResume();
        System.out.println("更新UI");
        detailsList = detailsManage.getAllDetailsByUsername(MySesseion.USER.getUsername());
        // 在这里执行与用户交互相关的操作，例如更新UI等
        update_top();
    }
    private void update_top() {


        double sum_in = 0, sum_out = 0, todaySumIn = 0, todaySumOut = 0;
        detailsList = detailsManage.getAllDetailsByUsername(MySesseion.USER.getUsername());
        for (Details details : detailsList) {
            System.out.println("零钱："+details.getDate());
            if (TimeUtility.isInCurrentMonth(details.getDate())) {
                System.out.println("零钱："+details.getMoney());
                if (details.getMoney() < 0) {
                    sum_out += details.getMoney();
                } else {
                    sum_in += details.getMoney();
                }
            }
            if (TimeUtility.isToday(details.getDate())) {
                System.out.println("零钱："+details.getMoney());
                if (details.getMoney() < 0) {
                    todaySumOut += details.getMoney();
                } else {
                    todaySumIn += details.getMoney();
                }
            }
        }
        YearMonth yearMonth = YearMonth.now();
        int daysInMonth = yearMonth.lengthOfMonth();
        double avgDailyExpenditure = sum_out / daysInMonth;

        DecimalFormat decimalFormat = new DecimalFormat("#.##");
        String formattedSumIn = decimalFormat.format(sum_in);
        String formattedSumOut = decimalFormat.format(sum_out);
        String formattedAvgDailyExpenditure = decimalFormat.format(avgDailyExpenditure);
        String formattedTodaySumIn = decimalFormat.format(todaySumIn);
        String formattedTodaySumOut = decimalFormat.format(todaySumOut);
        //System.out.println(detailsList.size());
        topOutTv.setText("￥" + formattedSumOut);
        topInTv.setText("￥" + formattedSumIn);
        topbudgetTv.setText("￥" + formattedAvgDailyExpenditure);
        topConTv.setText("今日支出￥" + formattedTodaySumOut + " 今日收入￥" + formattedTodaySumIn);
        //System.out.println("￥" + formattedSumOut+"\n￥" + formattedSumIn+"\n￥" + formattedAvgDailyExpenditure+"\n今日支出￥" + formattedTodaySumOut + " 今日收入￥" + formattedTodaySumIn);
    }

    private void addLVHeaderView() {
        // 将布局转换成view 对象
        headerView = getLayoutInflater().inflate(R.layout.item_main_top, null);
        todayLv.addHeaderView(headerView);
        // 初始化控件
        topOutTv = headerView.findViewById(R.id.item_mainlv_top_tv_out);
        topInTv = headerView.findViewById(R.id.item_main_top_tv_in);
        topbudgetTv = headerView.findViewById(R.id.item_mainlv_top_tv_budget);
        topConTv = headerView.findViewById(R.id.item_mainlv_top_tv_day);
//        topShowIv = headerView.findViewById(R.id.item_mainlv_top_iv_hide);

        topbudgetTv.setOnClickListener(this);
        headerView.setOnClickListener(this);


//        topShowIv.setOnClickListener(this);
    }

    private void setScrollListener() {
        //添加滑动事件监听
        todayLv.setOnScrollListener(new AbsListView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                // TODO Auto-generated method stub
                switch (scrollState) {
                    case SCROLL_STATE_FLING:
                        // 用户在手指离开屏幕之前，用力滑动一下，屏幕仍在下滑
                        btn_edit.setVisibility(View.INVISIBLE);
                        break;
                    case SCROLL_STATE_IDLE:
                        //视图已停止滑动"
                        btn_edit.setVisibility(View.VISIBLE);
                        break;
                    case SCROLL_STATE_TOUCH_SCROLL:
                        // "手指没有离开屏幕，视图正在滑动"
                        btn_edit.setVisibility(View.INVISIBLE);
                    default:
                        break;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
    }

    private void initTime() {
        Calendar calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH) + 1;
        day = calendar.get(Calendar.DAY_OF_MONTH);
    }

    @Override
    public void onClick(@NonNull View v) {
        Intent intent = null;
        System.out.println("监听");
        int id = v.getId();
        if (id == R.id.main_iv_search) {
            System.out.println("查询按钮");
//            intent = new Intent(requireContext(), SearchActivity.class);
//            startActivity(intent);
        } else if (id == R.id.main_btn_edit) {
            System.out.println("记一笔");
            // 在 DetailsFragment 中的某个方法中
            intent = new Intent(requireContext(), RecordActivity.class);
            startActivity(intent);
        }

        if (v == headerView) {
            // 头布局被点击了
            intent = new Intent(requireContext(), AnalyticsActivity.class);
            startActivity(intent);
        }
    }
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(0, MENU_UPDATE, 0, "修改记录");
        menu.add(0, MENU_DELETE, 0, "删除记录");
    }
    public boolean onContextItemSelected(MenuItem item) {
        //获取上下文菜单适配器
        AdapterView.AdapterContextMenuInfo cmi=(AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
        //获取被选择的菜单位置
        int posMenu=cmi.position;
        //将菜单项与列表视图的条目相关联
        Details bean=(Details) detailsAdapter.getItem(posMenu-1);
        switch(item.getItemId()){
            case 0://执行该菜单条目的业务逻辑
                Intent intent = new Intent();
                intent.setClass(requireContext(), RecordActivity.class);
                intent.putExtra("ListString", bean);
                this.startActivity(intent);
                break;
            case 1:
                showDeleteItemDialog(bean);
                break;
        }
        return super.onContextItemSelected(item);
    }
    private void setLVLongClickListener() {
        todayLv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) { // 表示点击了头布局
                    return false;
                }
                // 注意，position是从1开始的，而集合是从0开始的
                System.out.println(detailsList.size());
                int pos = position -1;
                Details clickBean = detailsList.get(pos); // 获取点击的位置
                // 弹出提示用户是否删除的对话框
                showDeleteItemDialog(clickBean);
                System.out.println(clickBean.toString());
                return false;
            }
        });
    }
    private void showDeleteItemDialog(final Details clickBean) {
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        builder.setTitle("提示信息").setMessage("您确定要删除该记录吗")
                .setNegativeButton("取消" , null)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        long click_id = clickBean.getId();
                        detailsManage.deleteItemFromAccounttbById(click_id);
                        // 执行删除操作
                        detailsList = detailsManage.getAllDetailsByUsername(MySesseion.USER.getUsername());
                        System.out.println(click_id+clickBean.toString());
                        System.out.println("元素个数"+detailsList.size());
                        detailsAdapter.updateDetailsList(detailsList);
                        detailsAdapter.notifyDataSetChanged(); // 提示适配器更新数据
                        update_top(); // 改变头布局TextView显示的内容
                    }
                });
        builder.create().show();
    }

}